package com.jinlia.show.modules.wxapp.service;

import com.jinlia.show.modules.base.system.entity.GoodsLabel;
import com.jinlia.show.modules.base.model.po.GoodsPO;
import com.jinlia.show.modules.base.system.service.GoodsLabelMapperService;
import com.jinlia.show.modules.base.system.service.GoodsLabelRelMapperService;
import com.jinlia.show.modules.base.model.po.GoodsLabelRelPO;
import com.jinlia.show.modules.base.model.po.GoodsLabelPO;
import com.jinlia.show.modules.base.model.query.GoodsLabelQuery;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class HomeService {

    @Autowired
    private GoodsLabelMapperService goodsTagMapperService;
    @Autowired
    private GoodsLabelRelMapperService goodsTagRelMapperService;



    public List<GoodsLabelPO> getGoodsLabel(GoodsLabelQuery goodsTagQuery) {
        //获取标签
        List<GoodsLabelPO> list = goodsTagMapperService.lambdaQuery()
                .in(!CollectionUtils.isEmpty(goodsTagQuery.getLabelIds()), GoodsLabel::getId, goodsTagQuery.getLabelIds())
                .in(!CollectionUtils.isEmpty(goodsTagQuery.getTagTitles()), GoodsLabel::getTitle, goodsTagQuery.getTagTitles())
                .list()
                .stream()
                .map(GoodsLabelPO::fromEntity)
                .collect(Collectors.toList());
        //标签ids
        List<Long> collectVO = list.stream().map(GoodsLabel::getId).collect(Collectors.toList());
        Map<Long, List<GoodsLabelRelPO>> goodsGroupByTags = goodsTagRelMapperService.getGoodsGroupByTags(collectVO);
        for (GoodsLabelPO goodsTagVO : list) {
            List<GoodsLabelRelPO> goodsTagRelVOS = goodsGroupByTags.get(goodsTagVO.getId());
            if (CollectionUtils.isEmpty(goodsTagRelVOS)) {
                goodsTagVO.setGoodsPOList(Arrays.asList());
            } else {
                List<GoodsPO> collect1 = goodsTagRelVOS.stream().map(GoodsLabelRelPO::getGoodsPO).collect(Collectors.toList());
                goodsTagVO.setGoodsPOList(collect1);
            }
        }
        return list;
    }
}
